﻿using PARK.Common.Core.Manager;
using PARK.Common.Enum;
using PARK.Common.Extension;
using PARK.Common.Filter;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using PARK.Common.Helper;
using PARK.JsonSerialization;
using PARK.Accessctl.Entitys;
using PARK.System.Entitys.Permission;
using PARK.Common.Util.SM4;
using PARK.System.Interfaces.Permission;
using PARK.Common.Util;
using System.Text;
using PARK.Attend.Interfaces.AttendAuth;
using PARK.Attend.Entitys;

namespace PARK.Accessctl.AccessCtlauth
{
    /// <summary>
    /// 考勤权限服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "Attend", Name = "Ctlauth", Order = 200)]
    [Route("api/Attend/[controller]")]
    public class AttendAuthService : IAttendAuthService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<AttendAuthEntity> _attendAuthRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;
        private readonly IOrganizeService _organizeService; // 机构表仓储

        /// <summary>
        /// 初始化一个<see cref="AttendAuthService"/>类型的新实例
        /// </summary>
        public AttendAuthService(
            ISqlSugarRepository<AttendAuthEntity> attendAuthRepository,
            IUserManager userManager,
            IOrganizeService organizeService)
        {
            _attendAuthRepository = attendAuthRepository;            
            _db = attendAuthRepository.Context;
            _userManager = userManager;
            _organizeService = organizeService;
        }

        /// <summary>
        /// 获取权限
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<AttendAuthEntity>().FirstAsync(p => p.Id == id);
            return entity;
        }
        /// <summary>
		/// 获取权限列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] AttendAuthListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var sidx = input.sidx == null ? "id" : input.sidx;
                var organizeIds = new List<string>();
                if (!input.organizeId.IsNullOrEmpty())
                    organizeIds = await GetSubOrganizeIds(input.organizeId);
                var data = await _db.Queryable<AttendAuthEntity>()
                    //公司权限
                    .Where(p => p.CompanyId.Equals(userInfo.companyId))
                    //组织机构
                    .WhereIF(organizeIds.Any(), u => organizeIds.Contains(SqlFunc.ToString(u.DepartId)))
                    //关键字查询
                    .WhereIF(!input.keyword.IsNullOrEmpty(), p => p.machSN.Contains(input.keyword) || p.CardNo.Contains(input.keyword) || p.JobNo.Contains(input.keyword) || p.ReallName.Contains(input.keyword))
                    .WhereIF(!string.IsNullOrEmpty(input.ctlSn), p => p.machSN.Contains(input.ctlSn))
                    .WhereIF(!string.IsNullOrEmpty(input.jobNo), p => p.JobNo.Contains(input.jobNo))
                    //所在区域
                    .WhereIF(!string.IsNullOrEmpty(input.doorAreaName), p => p.DoorAreaId.Equals(input.doorAreaName))
                    .Select(it => new AttendAuthListOutput
                    {
                        id = it.Id,
                        machlId = it.machlId,
                        machSN = it.machSN,
                        machName = it.machName,                       
                        jobNo = it.JobNo,
                        reallName = it.ReallName,
                        departName = it.DepartName,
                        cardNo = it.CardNo,
                        doorAreaName = it.DoorAreaName,
                        ctlposition = it.Ctlposition,
                        authStatus = it.AuthStatus
                    }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<AttendAuthListOutput>.SqlSugarPageResult(data);
            }
            else
                return null;
        }
        /// <summary>
        /// 下属机构
        /// </summary>
        /// <param name="organizeId">机构ID</param>
        /// <returns></returns>
        [NonAction]
        public async Task<List<string>> GetSubOrganizeIds(string organizeId)
        {
            var data = await _organizeService.GetListAsync();
            data = data.TreeChildNode(organizeId, t => t.Id, t => t.ParentId);
            return data.Select(m => m.Id).ToList();
        }

        /// <summary>
        /// 获取用户已经分配考勤
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetTransferdoorsByUser")]
        public async Task<dynamic> GetTransferdoorsByUser(string EmployeeId)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (string.IsNullOrEmpty(EmployeeId))
            {
                EmployeeId = "''";
            }
            var data = await _db.Queryable<AttendAuthEntity>()
                .Where(p => p.CompanyId.Equals(userInfo.companyId))//权限
                .Where(p => p.EmployeeId.Equals(EmployeeId))
                .Select(it => new AttendCtlTransferListOutput
                {
                    machlId = it.machlId,
                    machName = it.machName
                }).MergeTable().ToListAsync();
            return data;
        }
    }
}
